<?php
/**
 * Use base controller
 */
App::uses('Controller', 'Controller');

class AppController extends Controller {

    /**
     * Declare message function to load messages by function ID (screen ID)
     */
    public $messageFunction = '';

    /**
     * Set footer by specified screen
     */
    public $footer = 'footer';

    /**
     * Set header by specified screen
     */
    public $header = 'header';

    /**
     * Use smarty template
     */
    var $viewClass = 'Smarty';

    /**
     * Use model array
     */
    public $uses = array();
    /**
     * Use helper array
     */
    public $helpers = array(
                        'SmartyHtml',
                        'SmartyForm',
                        'SmartySession',
                        'SmartyJavascript',
                        'Html',
                        'IKYOCOMCommon'
                    );

    /**
     * Store logged-in user info
     */
    public $_userInfo = array();

    /**
     * Store system params
     */
    public $systemParam = array();

    /**
     * Flag to detect smartphone mode
     */
    public $isSmartPhone = FALSE;

    /**
     * Saves a variable as a html element for use inside a view template.
     * @param string|array $one A string or an array of data.
     * @param string|array $two Value in case $one is a string (which then works as the key).
     * @return void
     *
     */
    public function setHtmlElement($one, $two = null) {
        if (is_array($one)) {
            if (is_array($two)) {
                $data = array_combine($one, $two);
            } else {
                $data = $one;
            }
        } else {
            $data = array($one => $two);
        }
        $this->viewVars = $data + $this->viewVars;
    }

    /**
     * Function to get array of datas from a from (is get or posted from a screen)
     * @param array $allowedKeys Array of parameters that are accepted on a screen
     * @return array array of values with keys
     *
     */
    public function getFormDatas($alowedKeys = array()) {
        if (empty($alowedKeys)) {
            return NULL;
        }
        $formDatas = array();
        if ($this->request->is('post')) {
            $formDatas = $_POST;
        } else {
            $formDatas = $_GET;
        }

        if (!empty($formDatas)) {
            // Trim data
            $arrResults = array();
            foreach ($formDatas as $key => $value) {
                if (is_array($value)) {
                    $subValue = array();
                    foreach ($value as $k => $v) {
                        $v = $this->mb_trim($v);
                        if (isset($alowedKeys[$key]) && is_array($alowedKeys[$key]) && in_array($k, $alowedKeys[$key]) && $v !== '' && $v !== NULL
                        ) {
                            $subValue[$k] = $v;
                        }

                        if (!empty($subValue)) {
                            $arrResults[$key] = $subValue;
                        }
                    }
                } else {
                    $value = $this->mb_trim($value);
                    if (in_array($key, $alowedKeys) && $value !== '' && $value !== NULL) {
                        $arrResults[$key] = $value;
                    }
                }
            }
            return $arrResults;
        } else {
            return $formDatas;
        }
    }

    /**
     * Function to make condition to search (using paginator)
     * @param array $arrDatas array of fields with values that are used to make equal(=) condition for query
     * @param array $arrLike array of fields with values that are used to make LIKE condition for query
     * @param array $arrKeyword array of fields with values that are like a keyword (search by each of word in it)
     * @param array $modelNm name of the model
     * @return array Conditions that will be used to filter data from database
     *
     */
    public function makeSearchingConditions($arrDatas, $arrLike = array(), $arrKeyword = array(), $modelNm = '') {
        if (empty($arrLike)) {
            return $arrDatas;
        }

        if ($modelNm) {
            $modelNm .= '.';
        }

        $arrConditions = array();
        foreach ($arrDatas as $key => $value) {
            if (!empty($arrKeyword) && in_array($key, $arrKeyword)) {
                continue;
            }
            if (isset($arrLike[$key]) || in_array($key, $arrLike)) {
                if (is_array($value)) {
                    foreach ($value as $k => $v) {
                        if (is_array($arrLike[$key]) && in_array($k, $arrLike[$key])) {
                            $arrConditions["{$key}.{$k} like"] = "%{$v}%";
                        }
                    }
                } else {
                    $arrConditions["{$modelNm}{$key} like"] = "%{$value}%";
                }
            } else {
                if (is_array($value)) {
                    foreach ($value as $k => $v) {
                        $arrConditions["{$key}.{$k}"] = $v;
                    }
                } else {
                    $arrConditions["{$modelNm}{$key}"] = $value;
                }
            }
        }

        $arrKeywordConditions = array();
        foreach ($arrKeyword as $keyword) {
            if (!(isset($arrDatas[$keyword]) && $arrDatas[$keyword])) {
                continue;
            }
            //split keyword to word by word
            $parts_keyword = preg_split('/[\s,]+/', $arrDatas[$keyword]);
            foreach ($parts_keyword as $k) {
                $arrKeywordConditions[]["{$modelNm}{$keyword} like"] = "%{$k}%";
            }
        }
        if ($arrKeywordConditions) {
            $arrConditions = array('AND' => $arrConditions, 'OR' => $arrKeywordConditions);
        }
        return $arrConditions;
    }

    /**
     * Html encode an array
     * @param array $arr an array that you want to convert values into html entity
     * @return array an array with values that were converted into html entity
     *
     */
    public function htmlentities_array($arr) {
        //return true;
        foreach ($arr as $key => $value) {
            if (is_array($value)) {
                $arr[$key] = $this->htmlentities_array($value);
            } else {
                $arr[$key] = htmlentities($value, ENT_QUOTES, 'UTF-8');
            }
        }
        return $arr;
    }

    /**
     * Unicode trim string
     * @param string $string
     * @return string Return the string that is removed whitespace at the beginning and the end
     *
     */
    public function mb_trim($string) {
        $string = preg_replace("/(^\s+)|(\s+$)/us", "", $string);
        return $string;
    }

    /**
     * Unicode shows google map at a position
     * @return void
     *
     */
    public function showsMap() {
        $this->layout = '';
        $this->set('arrFormDatas', $this->getFormDatas(array('scale', 'lat', 'lng')));
        $this->render('/Maps/map');
    }

    /**
     * Unicode shows google map to choose a position
     * @return void
     *
     */
    public function choosePosition() {
        $this->layout = '';
        $this->set('arrFormDatas', $this->getFormDatas(array('scale', 'lat', 'lng')));
        $this->render('/Maps/choose_position');
    }

    /**
     * convert format code
     * @param int $num
     * @param int $len
     * @param string $ext
     * @return format 001
     *
     */
    public function formatNumber($num, $len, $ext) {
        return $ext . sprintf("%0" . $len . "d", $num);
    }

    /**
     * Check params for form
     * @param array $paramsCheck params-check
     * @return if check ok. return ''. else return list param not exist.
     *
     */
    public function checkFormParams($paramsCheck) {
        $formParams = array();
        if ($this->request->is('post')) {
            $formParams = $this->request->data;
        } else {
            $formParams = $_GET;
        }
        if (empty($formParams)) {
            $formParams = $this->passedArgs;
        }
        $result = '';
        foreach ($paramsCheck as $paramCheck => $paramCheckItem) {
            $fail = 1;
            foreach ($formParams as $paramForm => $paramIndex) {
                if (strtolower($paramCheckItem) == strtolower($paramForm)) {
                    $fail = 0;
                    break;
                }
            }
            if ($fail == 1) {
                $result .= $paramCheckItem . " ";
            }
        }
        return $result;
    }



}
